package team.stride.gmap;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

import team.stride.R;
import team.stride.utils.UtilsStride;
import android.graphics.Bitmap;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class Map extends MapActivity
{
	private MapView mapView;
	private MapController mapController;
	private MyLocationOverlay myLocationOverlay;
	private Bitmap mapBmp;

	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		mapView = (MapView) findViewById(R.id.mapview1);
		mapController = mapView.getController();
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		myLocationOverlay.enableMyLocation();
		myLocationOverlay.runOnFirstFix(new Runnable()
		{
			public void run()
			{
				mapController.animateTo(myLocationOverlay.getMyLocation());
			}
		});
		mapController.setZoom(12);

		mapView.setClickable(true);
		mapView.setEnabled(true);
		// mapView.setSatellite(true);
		mapView.displayZoomControls(true);
		mapView.setBuiltInZoomControls(true);
		if (UtilsStride.pathPoints.size() > 0)
		{
			mapController = mapView.getController();
			mapController.setZoom(12);
			GeoPoint po = new GeoPoint(UtilsStride.pathPoints.get(0).getLat(), UtilsStride.pathPoints.get(0).getLong());
			mapController.animateTo(po);
			PathDraw mapOverlay = new PathDraw(UtilsStride.pathPoints, this);
			List<Overlay> listOfOverlays = mapView.getOverlays();
			listOfOverlays.clear();
			listOfOverlays.add(mapOverlay);

			mapView.setClickable(true);
			mapView.setEnabled(true);
			// mapView.setSatellite(true);

			mapView.setBuiltInZoomControls(true);
			mapView.invalidate();
		}

	}

	@Override
	protected boolean isRouteDisplayed()
	{
		return false;
	}

	@Override
	public void onPause()
	{
		super.onPause();
		// save bmp
		if (!mapView.isDrawingCacheEnabled())
			mapView.buildDrawingCache();
		mapBmp = Bitmap.createBitmap(mapView.getDrawingCache());
		mapView.destroyDrawingCache();
	}

	public boolean saveMap(String path)
	{
		if (mapBmp == null)
			return false;
		FileOutputStream out;
		try
		{
			out = new FileOutputStream(path);
			mapBmp.compress(Bitmap.CompressFormat.JPEG, 25, out);
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
